<?php
namespace app\index\controller;

use \think\Controller;
use app\index\model\User as UserModel;

class Wechat extends Controller
{
     public $appid = null;
     public $appsecret = null;
     public $redirect = 'http://http://38h2b8.natappfree.cc/index.php/index/wechat/oauth';

     //构造函数，获取Access Token
     public function _initialize()
     {
         parent::_initialize();
         $this->appid = config('wechat.appid');
         $this->appsecret = config('wechat.app_secret');
     }

     //用户授权登录
     public function oauth()
     {
         if (!isset($_GET["code"])){
            $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
            $jumpurl = $this -> oauth2_authorize($redirect_url, "snsapi_userinfo", "123");
             $this->redirect($jumpurl);
         }else {
             echo $_GET['code'];die;
             $access_token_oauth2 = $this -> oauth2_access_token($_GET["code"]);
             $userinfo = $this -> oauth2_get_user_info($access_token_oauth2['access_token'], $access_token_oauth2['openid']);
//             dump($userinfo);die;
             //判断用户是否存在
             $user = new UserModel();
             $openid = $user -> where(['openid' => $userinfo['openid']]) -> value('openid');
             if(!$openid){
                 //注册入库
                 $user->data([
                     'nickname'  =>  $userinfo['nickname'],
                     'headimgurl' => $userinfo['headimgurl'],
                     'openid' => $userinfo['openid'],
                     'sex' => $userinfo['sex'],
                     'country' => $userinfo['country'],
                     'province' => $userinfo['province'],
                     'city' => $userinfo['city'],
                 ]);
                 $res = $user->save();
                 if($res){
                    return json(array('code' => 200,'msg' => '登录成功'));
                    session('uid',$user -> id);
                 }else{
                     return json(array('code' => -1,'msg' => '登录失败'));
                 }
             }else{
                 //用户已注册
                 $id = $user -> where(['openid' => $openid]) -> value('id');
                 $res = session('uid',$id);
                 if($res){
                     return json(array('code' => 200,'msg' => '登录成功'));
                 }else{
                     return json(array('code' => -2,'msg' => '登录失败'));
                 }
             }
         }
     }

     //生成OAuth2的URL
     public function oauth2_authorize($redirect_url, $scope, $state = NULL)
     {
         $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$redirect_url."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
         return $url;
     }

     //生成OAuth2的Access Token
     public function oauth2_access_token($code)
     {
           $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
         $res = $this->http_request($url);
         return json_decode($res, true);
     }

     //获取用户基本信息（OAuth2 授权的 Access Token 获取 未关注用户，Access Token为临时获取）
     public function oauth2_get_user_info($access_token, $openid)
     {
           $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
         $res = $this->http_request($url);
         return json_decode($res, true);
     }

     //获取用户基本信息
     public function get_user_info($openid)
     {
           $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
         $res = $this->http_request($url);
         return json_decode($res, true);
     }

     //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
     protected function http_request($url, $data = null)
     {
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_URL, $url);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
         if (!empty($data)){
             curl_setopt($curl, CURLOPT_POST, 1);
             curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
         }
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
         $output = curl_exec($curl);
         curl_close($curl);
         return $output;
     }
}